package aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import pojo.Customer;

@Component
@Aspect
public class MyDigestAspect {
	private final String p1= "execution(* service.CustomerManager.regist(..))";
	private final String p2= "execution(* service.CustomerManager.login(..))";
	
	private MessageDigest digest;
	
	
	public MyDigestAspect() {
		super();
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	@Around(value=p1)
	public Object regist(ProceedingJoinPoint point){
		Object o = null;
		
		
		Customer customer = (Customer) point.getArgs()[0];
		customer.setPassword(process(customer.getPassword()));
		try {
			o = point.proceed(new Object[]{customer});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	@Around(value=p2)
	public Object login(ProceedingJoinPoint point){
		Object o = null;
		
		String password = (String) point.getArgs()[1];
		try {
			o = point.proceed(new Object[]{point.getArgs()[0], process(password)});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	private String process(String s){
		String ss=null;
		try {
			byte[] bs=digest.digest(s.getBytes("ISO-8859-1"));
			ss=new String(bs,"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}
}
